package controller

import (
	"SE/Response"
	"SE/global"
	"SE/model"
	"SE/service"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

type CarController struct {
	carService service.CarService
}

func NewCarController(carController service.CarService) *CarController {
	return &CarController{carService: carController}
}

func CarList(c *gin.Context) {
	var carList []model.Car

	// 分页查询，offset，跳过多少记录
	err := global.DB.Limit(10).Offset(0).Find(&carList)

	if err.Error != nil {
		Response.Err(c, 400, "查询失败", err)
	}

	Response.Success(c, 200, "success", carList)
}

func (ca CarController) CarIn(c *gin.Context) {
	var car model.CarP
	err := c.ShouldBindJSON(&car)
	car.Status = 0
	if err != nil {
		Response.Err(c, 400, "参数错误", err)
		return
	}
	// 验证用户输入，车牌号,地点不能为空
	if car.PId == 0 || car.CarId == "" {
		Response.Err(c, 400, "车牌号不能为空", err)
		return
	}
	// 设置进入时间为本地时间
	car.InTime = time.Now()
	err = ca.carService.CarIn(car)
	if err != nil {
		Response.Err(c, 400, err, err)
		return
	}
	Response.Success(c, 200, "success", "进入成功")
}

func (ca CarController) CarOut(c *gin.Context) {
	id := c.Query("id")
	fmt.Println("id:", id)

	ids, err := strconv.Atoi(id)
	if err != nil {
		Response.Err(c, 400, "参数错误", err)
		return
	}
	pid, err := strconv.Atoi(c.Query("pid"))
	t, err := ca.carService.CarOut(ids, pid)
	if err != nil {
		Response.Err(c, 400, "查询失败", err)
		return
	}
	te := time.Now().Sub(t)
	//(te.Hours()*2)
	msg := "停留时间" + te.String() + "需要缴费" + fmt.Sprintf("%d", te.Hours()*2) + "元"
	Response.Success(c, 200, "success", msg)
}
